﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Net;
using System.Xml;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using JumbotPay.API.WxPayAPI;

using JumbotPay.API.Bdpay;
namespace JumbotPay.WebFile.Bdpay
{
    public partial class _order_query : JumbotPay.UI.BasicPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string _order_id = q("order_id");
            string _out_trade_no = q("out_trade_no");
            object[] value = new JumbotPay.DAL.OrderDAL().GetOrderFields("bdpay", _order_id, _out_trade_no, "appid,out_trade_no");
            string appid = value[0].ToString();
            _out_trade_no = value[1].ToString();

            //日志记录
            LogWriter logwriter = new LogWriter();


            string strXmlFile = HttpContext.Current.Server.MapPath("~/_data/config/payment_bdpay.config");
            JumbotPay.DBUtility.XmlControl XmlTool = new JumbotPay.DBUtility.XmlControl(strXmlFile);
            string sp_no = "sp_no=" + XmlTool.GetText("Root/sp_no");
            XmlTool.Dispose();

            string service_code = "service_code=11";
            string output_charset = "output_charset=1";
            //返回格式
            string output_type = "output_type=1";
            //版本
            string version = "version=2";
            string sign_method = "sign_method=2";
            //提交地址
            string BFB_QUERY_ORDER_URL = "https://www.baifubao.com/api/0/query/0/pay_result_by_order_no";
            /**
             *2、获取pay_unlogin.html页面提交的变量值_订单号
             */
            //订单号
            string order_no = "order_no=" + _out_trade_no;

            //给提交参数数值赋值
            string[] array ={
				order_no,
				output_type,
				output_charset,
				service_code,
				sign_method,
				sp_no,
				version};
            /**
             * 3、调用bfb_sdk_comm里create_baifubao_url方法生成百度钱包PC端即时到账支付接口URL(需要登录)
             *
             */
            string getURL = new JumbotPay.API.Bdpay.Common().create_baifubao_url(array, array, BFB_QUERY_ORDER_URL);
            /**
             * 4、向百度钱包发起订单查询请求
             */
            string data = "";
            HttpWebRequest webReqst = (HttpWebRequest)WebRequest.Create(getURL);
            webReqst.Method = "GET";
            webReqst.KeepAlive = true;
            //如果在接收后想保存CookieContainer并再次提交（比如登录后操作）  
            //必须保证url的域名前面有www，比如http://www.a.com，  
            webReqst.Timeout = 30000;

            /**
             *5、接收百度钱包返回数据,返回数据是XML格式
             */
            HttpWebResponse webResponse = (HttpWebResponse)webReqst.GetResponse();

            if (webResponse.StatusCode == HttpStatusCode.OK && webResponse.ContentLength < 1024 * 1024)
            {
                StreamReader reader = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.Default);
                data = reader.ReadToEnd();
                string streamString = data.Trim().Replace("\n", "");//去掉换行符

                /**
                 *6、解析XML
                 */
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(streamString);//加载文档

                //得到根节点下所有子节点。是一个list集合
                XmlNodeList selectNL = xmldoc.SelectNodes("response");
                XmlElement xmlEle;
                foreach (XmlNode node in selectNL)
                {
                    xmlEle = (XmlElement)node;
                    XmlNodeList childnode = xmlEle.ChildNodes;
                    //返回xml数据response的子节点个数
                    int count = childnode.Count;
                    //返回xml数据载入字符串数组arry
                    string[] arryTemp = new string[count];
                    string[] arry = new string[count - 1];
                    int i = 0;
                    System.Text.StringBuilder sb = new StringBuilder();
                    foreach (XmlNode xmlnode in childnode)
                    {
                        arryTemp[i] = xmlnode.Name + "=" + xmlnode.InnerText;
                        sb.AppendLine(arryTemp[i] + "<br/>");
                        i++;
                    }
                    //Response.Write(sb.ToString());
                    logwriter.appendToLog("百度钱包查询返回数据：" + sb.ToString(), Server.MapPath("~/Logs/NetLogBFB.log"));
                    for (int j = 0; j < count - 1; j++)
                    {
                        arry[j] = arryTemp[j];
                    }
                    /**
                     *7、调用签名方法Common().make_sign，对返回数据进行验证
                     */
                    string backSignTemp = arryTemp[count - 1];
                    string backSign = backSignTemp.Substring(backSignTemp.IndexOf("=") + 1);
                    string localSign = new JumbotPay.API.Bdpay.Common().make_sign(arry);
                    //Response.Write("百度钱包返回的签名：" + backSign + "<br/>");
                    //Response.Write("本地签名：" + localSign + "<br/>");
                    if (backSign.Equals(localSign))
                    {
                        //这里不要更新
                        //if (new JumbotPay.DAL.OrderDAL().UpdateOrder(appid, out_trade_no))
                        //{
                        //}
                        Response.Write(JsonResult(1, "success"));
                    }
                    else
                        Response.Write(JsonResult(0, sb.ToString()));
                }


            }
        }
    }
}